package com.poisonh.unifiedauth.service;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.poisonh.unifiedauth.R;

import java.io.File;

import okhttp3.Request;
import okhttp3.Response;


/**
 * 软件更新下载服务
 * Created by PoisonH on 2016/8/21.
 */
public class DownLoadService extends Service
{

    /**
     * 目标文件存储的文件夹路径
     */
    private String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "TYRZ";
    /**
     * 目标文件存储的文件名
     */
    private String destFileName = "年轮认证.apk";

    private Context mContext;
    private int preProgress = 0;
    private int NOTIFY_ID = 1000;
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        mContext = this.getApplicationContext();
        loadFile(intent.getStringExtra("URL"));
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    /**
     * 下载文件
     */
    private void loadFile(String url)
    {
        initNotification();
        OkHttpUtils.get(url).tag(this)
                .execute(new FileCallback(destFileDir, destFileName)
                {  //文件下载时，需要指定下载的文件目录和文件名
                    @Override
                    public void onResponse(boolean isFromCache, File file, Request request, Response response)
                    {
                        // file 即为文件数据，文件保存在指定目录
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed)
                    {
                        int pro = (int) ((float) currentSize / (float) totalSize * 100f);
                        updateNotification(pro);
                        if (currentSize == totalSize)
                        {
                            installApk(new File(destFileDir + File.separator + destFileName));
                        }
                    }
                });
    }


    /**
     * 安装软件
     *
     * @param file
     */
    private void installApk(File file)
    {
        Uri uri = Uri.fromFile(file);
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        // 执行意图进行安装
        mContext.startActivity(install);
    }


    /**
     * 初始化Notification通知
     */
    public void initNotification()
    {
        builder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("0%")
                .setContentTitle("年轮认证")
                .setProgress(100, 0, false);
        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFY_ID, builder.build());
    }

    /**
     * 更新通知
     */
    public void updateNotification(float progress)
    {
        int currProgress = (int) progress;
        if (preProgress < currProgress)
        {
            builder.setContentText(progress + "%");
            builder.setProgress(100, (int) progress, false);
            notificationManager.notify(NOTIFY_ID, builder.build());
        }
        preProgress = (int) progress;
    }

    /**
     * 取消通知
     */
    public void cancelNotification()
    {
        notificationManager.cancel(NOTIFY_ID);
    }
}
